import 'package:expensy_flutter/_inner_packages.dart';
import 'package:expensy_flutter/_external_packages.dart';
import 'package:expensy_flutter/screens/new_transaction_screen.dart';
import 'package:expensy_flutter/models/_models.dart';
import 'package:expensy_flutter/components/_components.dart';
import 'package:expensy_flutter/helpers/_helpers.dart';

class TransactionsScreen extends StatefulWidget {
  final String title;
  TransactionsScreen({Key key, this.title}) : super(key: key);

  @override
  _TransactionsScreenState createState() => _TransactionsScreenState();
}

class _TransactionsScreenState extends State<TransactionsScreen>
    with WidgetsBindingObserver {
  int touchedIndex;
  bool _showChart = true;
  bool _showPortraitOnly = false;

  void _touchCallbackHandler(BarTouchResponse barTouchResponse) {
    setState(() {
      if (barTouchResponse.spot != null &&
          barTouchResponse.touchInput is! PointerUpEvent &&
          barTouchResponse.touchInput is! PointerExitEvent) {
        touchedIndex = barTouchResponse.spot.touchedBarGroupIndex;
      } else {
        touchedIndex = -1;
      }
    });
  }

  void onSwitchShowChart(bool choice) {
    setState(() {
      _showChart = choice;
    });
  }

  void onSwitchPortraitOnLy(bool choice) {
    setState(() {
      _showPortraitOnly = choice;
    });
  }

  @override
  Widget build(BuildContext context) {
    AppData appData = Provider.of<AppData>(context, listen: true);
    Function closeAllThePanels = appData.closeAllThePanels; // Drawer related:
    bool isWeeklyFlChart = appData.isWeeklyFlChart;
    bool deviceIsIOS = DeviceHelper.deviceIsIOS(context);

    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      if (!_showPortraitOnly) ...[
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeRight,
      ],
    ]);

    TransactionsData transactionsData =
        Provider.of<TransactionsData>(context, listen: true);
    int amountTotalTransactions = transactionsData.transactions.length;

    ExpensyAppBar appBar = ExpensyAppBar(
      title: widget.title,
      showModalNewTransaction: () => _showModalNewTransaction(context),
    );

    return Scaffold(
      appBar: appBar,
      onDrawerChanged: (isOpened) {
        if (!isOpened) {
          closeAllThePanels();
        }
      },
      drawer: ExpensyDrawer(
        showChart: _showChart,
        onSwitchShowChart: onSwitchShowChart,
      ),
      body: NativeDeviceOrientationReader(
        builder: (context) {
          final orientation =
              NativeDeviceOrientationReader.orientation(context);
          bool safeAreaLeft = DeviceHelper.isLandscapeLeft(orientation);
          bool safeAreaRight = DeviceHelper.isLandscapeRight(orientation);
          bool isLandscape = DeviceHelper.isLandscape(orientation);

          return SafeArea(
            left: safeAreaLeft,
            right: safeAreaRight,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                if (_showChart) ...[
                  if (isWeeklyFlChart) ...[
                    Expanded(
                      flex: isLandscape ? 4 : 3,
                      child: TransactionsChart(
                        touchCallbackHandler: _touchCallbackHandler,
                        touchedIndex: touchedIndex,
                        groupedAmountLastWeek:
                            transactionsData.groupedAmountLastWeek(),
                        biggestAmountLastWeek:
                            transactionsData.biggestAmountLastWeek(),
                        orientation: orientation,
                      ),
                    ),
                  ] else ...[
                    Expanded(
                      flex: isLandscape ? 4 : 3,
                      child: TransactionsChartHomeMade(
                        groupedAmountLastWeek:
                            transactionsData.groupedAmountLastWeek(),
                        biggestAmountLastWeek:
                            transactionsData.biggestAmountLastWeek(),
                        orientation: orientation,
                      ),
                    ),
                  ],
                ],
                Expanded(
                  flex: 5,
                  child: TransactionsList(),
                ),
              ],
            ),
          );
        },
      ),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          children: [
            IconButton(icon: Icon(null), onPressed: () {}),
            Text(
              '总计: $amountTotalTransactions 条记录',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontStyle: FontStyle.italic,
                color: Colors.white,
              ),
            ),
          ],
        ),
        shape: CircularNotchedRectangle(),
        color: Theme.of(context).primaryColor,
      ),
      floatingActionButton: deviceIsIOS
          ? null
          : FloatingActionButton(
              tooltip: 'Add Transaction',
              child: Icon(Icons.add),
              onPressed: () => _showModalNewTransaction(context),
            ),
      floatingActionButtonLocation:
          deviceIsIOS ? null : FloatingActionButtonLocation.endDocked,
    );
  }

  void _showModalNewTransaction(BuildContext context) {
    SoundHelper().playSmallButtonClick();
    showModalBottomSheet(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (context) => NewTransactionScreen(),
    );
  }
}
